from django.db import models
from django.contrib.auth.models import User


class Book(models.Model):
    """书籍模型"""
    
    CONDITION_CHOICES = [
        ('new', '全新'),
        ('like_new', '几乎全新'),
        ('good', '良好'),
        ('fair', '一般'),
        ('poor', '较差'),
    ]
    
    STATUS_CHOICES = [
        ('available', '可售'),
        ('reserved', '已预订'),
        ('sold', '已售出'),
        ('offline', '已下架'),
    ]
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='书籍ID'
    )
    isbn = models.CharField(
        max_length=20,
        null=True,
        blank=True,
        db_index=True,
        verbose_name='ISBN编码',
        db_comment='ISBN编码'
    )
    title = models.CharField(
        max_length=200,
        verbose_name='书名',
        db_comment='书名'
    )
    author = models.CharField(
        max_length=100,
        verbose_name='作者',
        db_comment='作者'
    )
    publisher = models.CharField(
        max_length=100,
        verbose_name='出版社',
        db_comment='出版社'
    )
    publish_year = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='出版年份',
        db_comment='出版年份'
    )
    edition = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='版次',
        db_comment='版次'
    )
    category = models.CharField(
        max_length=50,
        db_index=True,
        verbose_name='书籍分类',
        db_comment='书籍分类'
    )
    major = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        db_index=True,
        verbose_name='相关专业',
        db_comment='相关专业'
    )
    cover_image = models.ImageField(
        upload_to='book_covers/',
        verbose_name='封面图片',
        db_comment='封面图片'
    )
    description = models.TextField(
        null=True,
        blank=True,
        verbose_name='书籍描述',
        db_comment='书籍描述'
    )
    original_price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='原价',
        db_comment='原价'
    )
    
    # 卖家信息
    seller = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='selling_books',
        verbose_name='卖家',
        db_comment='卖家ID'
    )
    price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='售价',
        db_comment='售价'
    )
    condition = models.CharField(
        max_length=20,
        choices=CONDITION_CHOICES,
        verbose_name='书籍成色',
        db_comment='书籍成色'
    )
    condition_score = models.DecimalField(
        max_digits=3,
        decimal_places=1,
        null=True,
        blank=True,
        verbose_name='AI成色评分',
        db_comment='AI成色评分(0-10)'
    )
    
    # 书籍状态
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='available',
        db_index=True,
        verbose_name='书籍状态',
        db_comment='书籍状态'
    )
    view_count = models.IntegerField(
        default=0,
        verbose_name='浏览次数',
        db_comment='浏览次数'
    )
    favorite_count = models.IntegerField(
        default=0,
        verbose_name='收藏次数',
        db_comment='收藏次数'
    )
    
    # 时间字段
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_index=True,
        verbose_name='创建时间',
        db_comment='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间',
        db_comment='更新时间'
    )
    sold_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='售出时间',
        db_comment='售出时间'
    )
    
    # AI相关字段
    ai_price_suggestion = models.JSONField(
        null=True,
        blank=True,
        verbose_name='AI价格建议',
        db_comment='AI价格建议'
    )
    defect_report = models.JSONField(
        null=True,
        blank=True,
        verbose_name='瑕疵检测报告',
        db_comment='瑕疵检测报告'
    )
    sale_probability = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        verbose_name='成交概率',
        db_comment='成交概率预测(0-100)'
    )
    
    class Meta:
        db_table = 'campus_book'
        db_table_comment = '书籍信息表'
        verbose_name = '书籍'
        verbose_name_plural = '书籍'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['seller', 'status']),
            models.Index(fields=['category', 'major']),
        ]
    
    def __str__(self):
        return self.title


class BookImage(models.Model):
    """书籍图片"""
    
    IMAGE_TYPE_CHOICES = [
        ('cover', '封面'),
        ('page', '内页'),
        ('defect', '瑕疵细节'),
    ]
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='图片ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='images',
        verbose_name='关联书籍',
        db_comment='关联书籍'
    )
    image = models.ImageField(
        upload_to='book_images/',
        verbose_name='图片文件',
        db_comment='图片文件'
    )
    image_type = models.CharField(
        max_length=20,
        choices=IMAGE_TYPE_CHOICES,
        verbose_name='图片类型',
        db_comment='图片类型'
    )
    defect_annotations = models.JSONField(
        null=True,
        blank=True,
        verbose_name='瑕疵标注',
        db_comment='AI标注的瑕疵位置'
    )
    uploaded_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='上传时间',
        db_comment='上传时间'
    )
    
    class Meta:
        db_table = 'campus_book_image'
        db_table_comment = '书籍图片表'
        verbose_name = '书籍图片'
        verbose_name_plural = '书籍图片'
        ordering = ['image_type', 'uploaded_at']
    
    def __str__(self):
        return f'{self.book.title} - {self.get_image_type_display()}'


class BookNote(models.Model):
    """书籍笔记"""
    
    NOTE_TYPE_CHOICES = [
        ('highlight', '重点标注'),
        ('annotation', '批注文字'),
        ('formula', '公式推导'),
        ('example', '例题解析'),
    ]
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='笔记ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='notes',
        verbose_name='关联书籍',
        db_comment='关联书籍'
    )
    chapter = models.CharField(
        max_length=100,
        verbose_name='章节',
        db_comment='章节名称'
    )
    page_range = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='页码范围',
        db_comment='页码范围'
    )
    note_image = models.ImageField(
        upload_to='book_notes/',
        verbose_name='笔记图片',
        db_comment='笔记图片'
    )
    extracted_text = models.TextField(
        null=True,
        blank=True,
        verbose_name='AI提取文字',
        db_comment='AI提取的笔记文字'
    )
    note_type = models.CharField(
        max_length=20,
        choices=NOTE_TYPE_CHOICES,
        verbose_name='笔记类型',
        db_comment='笔记类型'
    )
    keywords = models.JSONField(
        default=list,
        blank=True,
        verbose_name='关键词',
        db_comment='笔记关键词'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间',
        db_comment='创建时间'
    )
    
    class Meta:
        db_table = 'campus_book_note'
        db_table_comment = '书籍笔记表'
        verbose_name = '书籍笔记'
        verbose_name_plural = '书籍笔记'
        ordering = ['chapter', 'created_at']
    
    def __str__(self):
        return f'{self.book.title} - {self.chapter}'


class BookHistory(models.Model):
    """书籍流转历史"""
    
    id = models.BigAutoField(
        primary_key=True,
        verbose_name='编号',
        db_comment='历史ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='history',
        verbose_name='关联书籍',
        db_comment='关联书籍'
    )
    previous_owner = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name='上一任主人',
        db_comment='上一任主人'
    )
    transaction_price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        verbose_name='交易价格',
        db_comment='交易价格'
    )
    transaction_date = models.DateTimeField(
        verbose_name='交易日期',
        db_comment='交易日期'
    )
    condition_at_sale = models.CharField(
        max_length=20,
        verbose_name='售出时成色',
        db_comment='售出时成色'
    )
    
    class Meta:
        db_table = 'campus_book_history'
        db_table_comment = '书籍流转历史表'
        verbose_name = '流转历史'
        verbose_name_plural = '流转历史'
        ordering = ['-transaction_date']
    
    def __str__(self):
        return f'{self.book.title} - {self.transaction_date.strftime("%Y-%m-%d")}'
